// watch.js

const observe = (obj, key, watchFun, deep, page) => {
    let oldVal = obj[key]
    if (oldVal !== null && typeof oldVal === 'object' && deep) {
      // 递归子集，依次执行observe()
      Object.keys(oldVal).forEach(item => {
        observe(oldVal, item, watchFun, deep, page)
      })
    }
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set(value) {
        if (value === oldVal) return
        watchFun.call(page, value, oldVal)
        oldVal = value
      },
      get() {
        return oldVal
      }
    })
  }

  export const setWatcher = (page) => {
    const data = page.data
    const watch = page.watch
    Object.keys(watch).forEach(key => {
      let targetData = data
      const targetKey = key
      // 支持deep深度监听，使用deep时需要配合handler使用，否则直接编写函数
      const watchFun = watch[key].handler || watch[key]
      const deep = watch[key].deep
      observe(targetData, targetKey, watchFun, deep, page)
    })
  }


//封装watch监听
//首先获取页面数据
// export const setWatcher = (page) => {
//   let data = page.data
//   let watch = page.watch
//   for (var i in watch) {
//     let watchArr = i.split('.') 
//     let oldData = data; 
//     let watchFun = watch[i].handler || watch[i]; // 兼容带handler和不带handler的两种写法
//     let deep = watch[i].deep; // 若未设置deep,则为undefine
//     observe(oldData, watchArr, watchFun, deep, page);

//   }
// }

// const observe = (obj, key, watchFun, deep, page) => {
//   let val = obj[key]
//   if (deep && val != null && typeof val === 'object') {
//     for (let i in val) {
//       observe(val, i, watchFun, deep, page); // 递归调用监听函数
//     }
//   }
//   Object.defineProperty(obj, key, {
//     configurable: true, 
//     enumerable: true, 
//     set: function (value) {
//       watchFun.call(page, value, val); 
//       val = value;
//       if (deep) { 
//         observe(obj, key, watchFun, deep, page);
//       }
//     },
//     get: function () {
//       return val;
//     }
//   })
// }